package cn.stylefeng.guns.modular.system.service.Myservice;

import cn.stylefeng.guns.modular.system.entity.InventoryOrder;
import cn.stylefeng.guns.modular.system.entity.InventorySales;
import cn.stylefeng.guns.modular.system.model.params.paramsDTO.CheckDTO;
import cn.stylefeng.guns.modular.system.service.InventoryOrderService;
import cn.stylefeng.guns.modular.system.service.InventorySalesService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 通用服务层
 * @Author : xiaofei
 * @Date: 2019/7/9
 */
@Service
public class CommonService {


    @Autowired
    private InventoryOrderService inventoryOrderService;
    @Autowired
    private InventorySalesService inventorySalesService;

    /**
     * 通用入库单
     * @param checkDTO
     */
   public void salsOutOrder(CheckDTO checkDTO){

       List<CheckDTO.InventorySales> lists = JSON.parseArray(checkDTO.getInventorySales(),CheckDTO.InventorySales.class);
       lists.forEach((s) -> {
           InventorySales inventorySales = new InventorySales();
           BeanUtils.copyProperties(s,inventorySales);
           inventorySales.setDispatchOrderId(checkDTO.getId());
           inventorySales.setSerialNum(StringUtils.join(s.getSerials(),","));
           inventorySalesService.save(inventorySales);

           //查询出刚插入数据库中的出库id
           InventorySales inventorySalesLast = inventorySalesService.getOne(new QueryWrapper<InventorySales>()
           .lambda().orderByDesc(InventorySales::getId).last("limit 1"));
           //更新库存表中的信息
           InventoryOrder inventoryOrder = inventoryOrderService.getById(s.getInventoryOrderId());
           inventoryOrder.setAmount(inventoryOrder.getAmount() - s.getAmount());
           List<String> serialsOld = Arrays.asList(inventoryOrder.getSerialNum().split(","));
           s.getSerials().forEach(e ->{
               serialsOld.stream().filter((o) -> e.equals(o)).collect(Collectors.toList());
           });
           inventoryOrder.setSerialNum(StringUtils.join(serialsOld,","));
           inventoryOrder.setSerialNumOut(StringUtils.join(s.getSerials().toArray(),","));
       });
   }
}
